package T05_JDBCUtils中使用DBCP数据库连接池.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 *
 */
public class JDBCUtils{

    //静态类属性
    private  static   DataSource dataSource;

    //静态代码块
    static {
        try {
            Properties pros = new Properties();
            //方式1：
            //InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
            //方式2：
            FileInputStream is = new FileInputStream(new File("src/dbcp.properties"));
            pros.load(is);
            //创建一个DBCP数据库连接池
            dataSource = BasicDataSourceFactory.createDataSource(pros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用DBCP获取数据库连接
     * @return
     * @throws SQLException
     */
    public  static  Connection  getConnection() throws Exception {
        Connection conn = dataSource.getConnection();
        System.out.println(conn);
        return  conn;
    }

    /**
     * 关闭连接和Statement的操作1
     * @param conn
     * @param statement
     */
    public  static void  closeResource(Connection conn, Statement statement){
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接和Statement的操作2
     * @param conn
     * @param statement
     * @param resultSet
     */
    public  static void  closeResource(Connection conn, Statement statement, ResultSet resultSet){
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
